package com.daoliuhe.scaffold.service.impl;

import com.daoliuhe.scaffold.mapper.RoleAuthoritiesRelationMapper;
import com.daoliuhe.scaffold.mapper.UserGroupRoleMapper;
import com.daoliuhe.scaffold.mapper.UserMapper;
import com.daoliuhe.scaffold.mapper.UserRoleRelationMapper;
import com.daoliuhe.scaffold.model.Authorities;
import com.daoliuhe.scaffold.model.Role;
import com.daoliuhe.scaffold.model.User;
import com.daoliuhe.scaffold.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;


@Service
public class UserServiceImpl implements UserService {

	private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

	@Autowired
	UserMapper userMapper;

	@Autowired
	UserRoleRelationMapper userRoleRelationMapper;

	@Autowired
	UserGroupRoleMapper userGroupRoleMapper;

	@Autowired
	RoleAuthoritiesRelationMapper roleAuthoritiesRelationMapper;

	@Override
	public User getUserByUserName(String userName) {
		logger.info("getUserByUserName,userName:{}",userName);
		return userMapper.getUserByUserName(userName);
	}

	@Override
	public User getUserByLoginId(String loginId) {
		logger.info("getUserByLoginId,loginId:{}",loginId);
		return userMapper.getUserByLoginId(loginId);
	}

	@Override
	public Map<String, Object> getPageData(User user) {
		logger.info("getPageData,user:{}",user);
		Map<String, Object> map = new HashMap<String, Object>();
		int total = userMapper.getPageCount(user);
		map.put("total", total);
		int curPage = user.getPage();
		int rows = user.getRows();
		int maxPage = (total + rows - 1) / rows;
		if (curPage > maxPage && maxPage > 0) {
			user.setPage(maxPage);
		}
		map.put("rows", userMapper.getPageData(user));
		return map;
	}

	@Override
	public void saveOrUpdate(User user) {
		logger.info("saveOrUpdate,user:{}",user);
		if (!StringUtils.isEmpty(user.getId())) {
			userMapper.updateByPrimaryKey(user);
		} else {
			//String password = BCrypt.hashpw(Config.CODE, BCrypt.gensalt(12));
			//user.setUserPassword(password);
			userMapper.insert(user);
		}
	}

	@Override
	public User getUserById(String id) {
		logger.info("getUserById,id:{}",id);
		User u = userMapper.getUserById(id);
		//u.setProductLine(u.getProductLineStr());
		return u;
	}

	/**
	 * 是否为合理的工号
	 */
	@Override
	public boolean isRightLoginId(String loginId, String id) {
		logger.info("isRightLoginId,loginId:{},id:{}",loginId,id);
		boolean flag = false;
		if (StringUtils.isEmpty(id)) {
			flag = userMapper.getUserByLoginId(loginId) == null;
		} else {
			User user = userMapper.getUserById(id);
			if (user != null) {
				flag = user.getLoginId().equals(loginId);
				if (!flag) {
					flag = userMapper.getUserByLoginId(loginId) == null;
				}
			}
		}
		return flag;
	}

	/**
	 * 查找select2的格式数据
	 */
	@Override
	public Object selectUser(String param) {
		logger.info("selectUser,param:{}",param);
		List<User> list = userMapper.selectUser(param);
		return list;
	}

	@Override
	public Set<String> getRolesByUserLoginId(String loginId) {
		logger.info("getRolesByUserLoginId,loginId:{}",loginId);
		Set<String> roleSet = new HashSet<String>();
		//根据用户查询角色
		List<Role> roleList = userRoleRelationMapper.getRolesByUserLoginId(loginId);
		//根据用户查询关联的用户组，用户组管理的角色
		List<Role> userGroupRoleList = userGroupRoleMapper.getRolesByUserLoginId(loginId);
		for (Role role : roleList) {
			roleSet.add(role.getName());
		}
		for (Role role : userGroupRoleList) {
			roleSet.add(role.getName());
		}
		return roleSet;
	}

	@Override
	public Set<Role> getRolesByLoginId(String loginId) {
		logger.info("getRolesByLoginId,loginId:{}",loginId);
		Set<Role> roleSet = new HashSet<Role>();
		//根据用户查询角色
		List<Role> roleList = userRoleRelationMapper.getRolesByUserLoginId(loginId);
		//根据用户查询关联的用户组，用户组管理的角色
		List<Role> userGroupRoleList = userGroupRoleMapper.getRolesByUserLoginId(loginId);
		roleSet.addAll(roleList);
		roleSet.addAll(userGroupRoleList);
		return roleSet;
	}

	@Override
	public Set<String> getPermissionsByRoles(Set<Role> roles) {
		logger.info("getPermissionsByRoles,roles:{}",roles);
		Set<String> set = new HashSet<String>();
		if (!roles.isEmpty()) {
			List<String> param = new ArrayList<String>();
			for (Role role : roles) {
				param.add(role.getId());
			}
			//根据角色id,查询相关的权限
			List<Authorities> list = roleAuthoritiesRelationMapper.getAuthByRoles(param);
			for (Authorities auth : list) {
				set.add(auth.getPermission());
			}
		}
		return set;
	}

	@Override
	public Set<String> getPermissionsByUserLoginId(String loginId) {
		logger.info("getPermissionsByUserLoginId,loginId:{}",loginId);
		Set<String> set = new HashSet<String>();
		List<Authorities> list = roleAuthoritiesRelationMapper.getAuthByLoginId(loginId);
		for (Authorities auth : list) {
			set.add(auth.getPermission());
		}
		return set;
	}

	@Override
	public void updateUser(User user) {
		logger.info("updateUser,user:{}",user);
		userMapper.updateByPrimaryKeySelective(user);
	}

	@Override
	public void updateBatchEnable(ArrayList<String> ids) {
		logger.info("batchEnable,ids:{}",ids);
		userMapper.updateBatchEnable(ids);		
	}

	@Override
	public void updateBatchDisable(ArrayList<String> ids) {
		logger.info("batchDisable,ids:{}",ids);		
		userMapper.updateBatchDisable(ids);
	}
	
	@Override
	public List<User> getUsersByIds(String ids) {
		logger.info("getUsersByIds,ids:{}",ids);
		List<User> retList = new ArrayList<User>();
		if (null != ids && !ids.isEmpty()) {
			String[] strs = ids.split(",");
			retList = userMapper.getUsersByIds(Arrays.asList(strs));
		}
		return retList;
	}
}
